package com.heima.article.task;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.heima.article.entity.ApArticle;
import com.heima.article.entity.ApArticleContent;
import com.heima.article.service.IApArticleService;
import com.heima.common.minio.MinIOService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ArticleHtmlTask {

    @Autowired
    private IApArticleService apArticleService;
    @Autowired
    private Configuration configuration;
    @Autowired
    private MinIOService minIOService;

    @Async
    public void createHtml(ApArticle apArticle, String content){
        try {
            Long articleId= apArticle.getId();
            List<Map> mapList = JSON.parseArray(content, Map.class);

            Map dataModel = new HashMap();
            dataModel.put("content",mapList);

            StringWriter writer = new StringWriter();
            Template template = configuration.getTemplate("article.ftl");
            template.process(dataModel,writer);
//        把生成的文件放到minIO中
            ByteArrayInputStream inputStream = new ByteArrayInputStream(writer.toString().getBytes());
            String url = minIOService.upload("article/"+articleId+".html",inputStream,"text/html");
//        更新ap_article中的static_url的值
//        update ap_article set static_url =? where id=??
            apArticle.setStaticUrl(url);
            apArticleService.updateById(apArticle);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
